package com.jeesite.modules.jdProduct.web;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.responseReturn.entity.ResultObject;
import com.jeesite.common.responseReturn.utils.CommonUtils;
import com.jeesite.common.responseReturn.web.Render;
import com.jeesite.modules.goods.entity.ZtGoodsOrder;
import com.jeesite.modules.goods.service.ZtGoodsOrderService;
import com.jeesite.modules.jdProduct.dao.dto.*;
import com.jeesite.modules.jdProduct.entity.ZtAfterSale;
import com.jeesite.modules.jdProduct.service.ZtAfterSaleService;
import com.jeesite.modules.jdProduct.utils.AfsServiceEnum;
import com.jeesite.modules.jdProduct.utils.AfterSaleUtils;
import com.jeesite.modules.jdProduct.utils.GsonUtil;
import com.jeesite.modules.jdProduct.utils.ProductPoolUtils;
import com.jeesite.modules.jdProduct.vo.*;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName AppZtAfterSaleController
 * @description   售后接口
 * @Author ouyang
 * @Date 2019/4/29 16:29
 **/
@Controller
@RequestMapping(value = "${frontPath}/afterSale")
public class AppZtAfterSaleController {


    @Autowired
    private ZtGoodsOrderService ztGoodsOrderService;
    @Autowired
    private ZtAfterSaleService ztAfterSaleService;




    @RequestMapping(value = "list")
    @ResponseBody
    public void goodsList(HttpServletRequest request, HttpServletResponse response){
        String paramStr = CommonUtils.getParams(request);
        JSONObject jo = JSONObject.parseObject(paramStr);
        String adminid = jo.getString("adminid");
        String pageNum = "1";
        if (!StringUtils.isEmpty(jo.getInteger("pageNum"))) {
            pageNum = jo.get("pageNum").toString();
        }
        ResultObject res = new ResultObject();
        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        ZtAdmin admin = new ZtAdmin();
        admin.setId(adminid);
        ztGoodsOrder.setZtAdmin(admin);
        // 0 未付款 1 已付款 2 代发货 3 已完成 4 取消
        ztGoodsOrder.setOrderstatus("3");
        ztGoodsOrder.setPageNum((Integer.valueOf(pageNum) - 1) * 15);
        List<ZtGoodsOrder> list = ztGoodsOrderService.findGhMh(ztGoodsOrder);
        List<AfterSaleListVo> listVos = new ArrayList<>();
        for (ZtGoodsOrder order : list) {
            AfterSaleListVo vo = new AfterSaleListVo();
            vo.setOrderId(order.getId());
            vo.setImg(order.getZtGoods().getImg());
            vo.setTitle(order.getZtGoods().getTitle());
            vo.setNumCount(order.getNumCount());
            vo.setOrderTime(order.getOrderTime());
            vo.setSalestatus(order.getSalestatus());
            vo.setSpotid(order.getSpotid());
            listVos.add(vo);
        }
        res.setData(listVos);
        res.setResult(200L);
        Render.renderString(response, res);
    }


    /**
     *  售后列表
     * @param request
     * @param response
     */
    @RequestMapping(value = "listData")
    @ResponseBody
    public void listData(HttpServletRequest request, HttpServletResponse response){
        String paramStr = CommonUtils.getParams(request);
        JSONObject jo = JSONObject.parseObject(paramStr);
        ResultObject res = new ResultObject();
        ZtAfterSale afterSale = new ZtAfterSale();
        String pageNum = "1";
        if (!StringUtils.isEmpty(jo.getInteger("afsServiceStep"))) {
            afterSale.setAfsServiceStep(jo.getInteger("afsServiceStep"));
        }
        if (!StringUtils.isEmpty(jo.getInteger("pageNum"))) {
            pageNum = jo.get("pageNum").toString();
        }
        String adminid = jo.getString("adminid");
        afterSale.setAdminId(adminid);
        afterSale.setPageNum((Integer.valueOf(pageNum) - 1) * 15);
        List<ZtAfterSale> saleList = ztAfterSaleService.findGhMh(afterSale);
        List<AfterSaleListVo> saleListVos = new ArrayList<>();
        for (ZtAfterSale list:saleList
             ) {
            AfterSaleListVo vo = new AfterSaleListVo();
            vo.setSaleId(list.getId());
            vo.setTitle(list.getWareName());
            vo.setImg(list.getImg());
            vo.setAfsServiceId(list.getAfsServiceId());
            vo.setNumCount(list.getNum());
            vo.setSalestatus(String.valueOf(list.getAfsServiceStep()));
            saleListVos.add(vo);
        }
        res.setResult(200L);
        res.setData(saleListVos);
        Render.renderString(response, res);
    }

    /**
     *  售后详情
     * @param request
     * @param response
     */
    @RequestMapping(value = "details")
    @ResponseBody
    public void details(HttpServletRequest request, HttpServletResponse response){
        String paramStr = CommonUtils.getParams(request);
        JSONObject jo = JSONObject.parseObject(paramStr);
        ResultObject res = new ResultObject();
        ZtAfterSale afterSale = new ZtAfterSale();
        String saleId = jo.getString("saleId");
        afterSale.setId(saleId);

        afterSale = ztAfterSaleService.get(afterSale);
        ZtGoodsOrder goodsOrder = new ZtGoodsOrder();
        goodsOrder.setId(afterSale.getOrder());
        goodsOrder = ztGoodsOrderService.get(goodsOrder);
        AfterSaleDetailsVo detailsVo = new AfterSaleDetailsVo();
        if(goodsOrder.getSpotid()==1){
            if (StringUtils.isEmpty(afterSale.getAfsServiceId())) {
                //如果为空 则在查询一次以便获取服务单好
                saveServiceSingle(goodsOrder.getChannelorder(),afterSale.getId());
                afterSale = ztAfterSaleService.get(afterSale);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtils.isEmpty(afterSale.getAfsServiceId())) {
                params.put("afsServiceId", afterSale.getAfsServiceId());
                params.put("appendInfoSteps", Arrays.asList(1, 2, 4, 5));
                ServiceDetailInfoDto dto = ProductPoolUtils.queryServiceDetailInfo(GsonUtil.toJson(params));
                if (StringUtils.isEmpty(dto)) {
                    res.setResult(400L);
                    res.setMsg("参数错误!");
                    Render.renderString(response, res);
                    return;
                }
                BeanUtils.copyProperties(dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult(), afterSale);
                //ztAfterSaleService.update(afterSale);  让轮巡去更新

                BeanUtils.copyProperties(afterSale, detailsVo);
                BeanUtils.copyProperties(goodsOrder, detailsVo);
                detailsVo.setId(afterSale.getId());
                detailsVo.setTitle(afterSale.getWareName());
                detailsVo.setNumCount(afterSale.getNum());
                detailsVo.setType(getServiceType(afterSale.getType()));
                detailsVo.setTakeType(getTakeType(afterSale.getTakeType()));
                detailsVo.setTotalPrice(goodsOrder.getTotalPrice());
                detailsVo.setServiceTrackInfoDTOs(dto.getBiz_afterSale_serviceDetailInfo_query_response().getResult().getServiceTrackInfoDTOs());
                detailsVo.setStatus(Integer.valueOf(afterSale.getAfsServiceStep()));
                detailsVo.setSpotid(1);
                res.setResult(200L);
                res.setData(detailsVo);
                Render.renderString(response, res);
                return;
            }
        }else {
            detailsVo.setId(afterSale.getId());
            detailsVo.setTitle(afterSale.getWareName());
            detailsVo.setNumCount(afterSale.getNum());
            detailsVo.setImg(afterSale.getImg());
            detailsVo.setAfsApplyTime(afterSale.getAfsApplyTime());
            detailsVo.setType(getServiceType(afterSale.getType()));
            detailsVo.setTakeType(getTakeType(afterSale.getTakeType()));
            detailsVo.setTotalPrice(goodsOrder.getTotalPrice());
            detailsVo.setStatus(Integer.valueOf(afterSale.getAfsServiceStep()));
            detailsVo.setSpotid(0);
            detailsVo.setReason(afterSale.getReason());
            detailsVo.setTakeAddr(afterSale.getTakeAddr());
            detailsVo.setReturnAddr(afterSale.getReturnAddr());
            detailsVo.setExpressCode(afterSale.getExpressCode());
            detailsVo.setFreightMoney(afterSale.getFreightMoney());
            detailsVo.setExpressCompany(afterSale.getExpressCompany());
            detailsVo.setDeliverDate(afterSale.getDeliverDate());
            res.setResult(200L);
            res.setData(detailsVo);
            Render.renderString(response, res);
            return;
        }
        res.setResult(400L);
        res.setMsg("参数错误!");
        Render.renderString(response, res);
    }

    /**
     * 设置状态
     * @param afterSale
     * @param detailsVo
     */
    private Integer setStatus(ZtAfterSale afterSale, AfterSaleDetailsVo detailsVo) {

        //申请中
        if (AfterSaleUtils.apply.contains(afterSale.getAfsServiceStep())) {
               return 1;
        }else
        //收货中
        if (AfterSaleUtils.receipt.contains(afterSale.getAfsServiceStep())) {

            return 2;
        }else
        //处理中
        if (AfterSaleUtils.handle.contains(afterSale.getAfsServiceStep())) {
            return 3;
        }else
        //完成
        if (AfterSaleUtils.complete.contains(afterSale.getAfsServiceStep())) {
           return 4;
        }else
        //审核不通过
        if (afterSale.getAfsServiceStep().equals(20)) {
            return 5;
        }else
        //取消
        if (afterSale.getAfsServiceStep().equals(60)) {
            return 6;

        }else {
            return 0;//异常
        }
    }

    /** 获取取件方式*/
    private String getTakeType(Integer takeType) {
        String type = null;
        switch (takeType) {
            case 4:
                type = "上门取件";
                break;
            case 7:
                type = "客户送货";
                break;
            case 40:
                type = "客户发货";
                break;
            default:
                type = "上门取件";
        }
        return type;
    }


    /**
     *  选择售后类型
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "select")
    @ResponseBody
    public void afterSaleService(HttpServletRequest request,
                                  HttpServletResponse response, Model model){
        ResultObject res = new ResultObject();
        Map<String, Object> params = shareParameter(request, res);
        if (StringUtils.isEmpty(params)) {
            Render.renderString(response, res);
            return;
        }
        ZtGoodsOrder ztGoodsOrder = (ZtGoodsOrder) params.get("order");
        ServiceTypeVo saleVo = new ServiceTypeVo();
        if(params.get("spotid").toString().equals("1")) {
            params.remove("spotid");
            params.remove("order");
            AfterSaleDto dto = ProductPoolUtils.afterSale(GsonUtil.toJson(params));
            if (dto.getAfterSale().isSuccess()) {
                List<AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean> serviceType = ProductPoolUtils.afterSaleStandByProduct(GsonUtil.toJson(params));
                if (serviceType.size() > 0) {
                    for (AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean service : serviceType
                    ) {
                        switch (service.getCode()) {
                            case "10":
                                service.setDepict("退掉已收到的商品");
                                break;
                            case "20":
                                service.setDepict("更换收到的商品");
                                break;
                            case "30":
                                service.setDepict("维修收到的商品");
                                break;
                        }
                        saleVo.setImg(ztGoodsOrder.getZtGoods().getImg());
                        saleVo.setNumCount(ztGoodsOrder.getNumCount());
                        saleVo.setTitle(ztGoodsOrder.getZtGoods().getTitle());

                    };
                    saleVo.setServiceType(serviceType);
                    saleVo.setOrderTime(ztGoodsOrder.getOrderTime());
                    saleVo.setSalestatus(ztGoodsOrder.getSalestatus());
                    res.setResult(200L);
                    res.setData(saleVo);
                    Render.renderString(response, res);
                    return;
                }


            } else {
                res.setResult(400L);
                res.setData(dto.getAfterSale());
                Render.renderString(response, res);
                return;
            }
        }else {
            saleVo.setImg(ztGoodsOrder.getZtGoods().getImg());
            saleVo.setNumCount(ztGoodsOrder.getNumCount());
            saleVo.setTitle(ztGoodsOrder.getZtGoods().getTitle());
            saleVo.setServiceType(serviceType());
            saleVo.setOrderTime(ztGoodsOrder.getOrderTime());
            saleVo.setSalestatus(ztGoodsOrder.getSalestatus());
            res.setResult(200L);
            res.setData(saleVo);
            Render.renderString(response, res);
            return;
        }
    }


    /**
     *  申请售后
     * @param request
     * @param response
     */
    @RequestMapping(value = "applyFor")
    @ResponseBody
    public void applyForAfterSale(HttpServletRequest request,HttpServletResponse response){
        ResultObject res = new ResultObject();
        Map<String, Object> params = shareParameter(request, res);
        if (StringUtils.isEmpty(params)) {
            return;
        }

        ZtGoodsOrder ztGoodsOrder = (ZtGoodsOrder) params.get("order");
        AfterSaleVo saleVo = new AfterSaleVo();
        if(params.get("spotid").toString().equals("1")) {
            params.remove("order");

            List<StandByProductDto.StandByProduct.ResultBean> resultBeans = ProductPoolUtils.standByProduct(GsonUtil.toJson(params));
            if (resultBeans.size() > 0) {
                saleVo.setResultBeans(resultBeans);
                BeanUtils.copyProperties(ztGoodsOrder, saleVo);
                saleVo.setDetails(ztGoodsOrder.getDetailaddr());
                saleVo.setImg(ztGoodsOrder.getZtGoods().getImg());
                saleVo.setTitle(ztGoodsOrder.getZtGoods().getTitle());
                saleVo.setNumCount(ztGoodsOrder.getNumCount());
                saleVo.setSpotid(1);
                res.setResult(200L);
                res.setData(saleVo);
                Render.renderString(response, res);
                return;
            }
        }else {
            BeanUtils.copyProperties(ztGoodsOrder, saleVo);
            saleVo.setDetails(ztGoodsOrder.getDetailaddr());
            saleVo.setImg(ztGoodsOrder.getZtGoods().getImg());
            saleVo.setTitle(ztGoodsOrder.getZtGoods().getTitle());
            saleVo.setNumCount(ztGoodsOrder.getNumCount());
            saleVo.setSpotid(0);
            res.setResult(200L);
            res.setData(saleVo);
            Render.renderString(response, res);
            return;
        }
        res.setResult(400L);
        res.setMsg("内部异常!");
        Render.renderString(response, res);
        return;
    }


    /**
     *  创建服务单
     * @param request
     * @param response
     */
    @PostMapping(value = "create")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public void createService(HttpServletRequest request,HttpServletResponse response){
        String paramStr=CommonUtils.getParams(request);
        JSONObject jo=JSONObject.parseObject(paramStr);
        ResultObject res = new ResultObject();
        if (StringUtils.isEmpty(jo.getString("returnAddr")) & StringUtils.isEmpty(jo.getString("adminid"))) {
            res.setResult(400L);
            res.setMsg("非法参数!");
            Render.renderString(response, res);
        }


        //订单号
        String orderId = jo.getString("orderId");
        //客户预期（退货(10)、换货(20)、维修(30)）
        Integer customerExpect = jo.getInteger("customerExpect");
        //产品问题描述
        String questionDesc = jo.getString("questionDesc");
        //问题描述图片 url1,url2
        String questionPic = jo.getString("questionPic");
        // 取件方式
        Integer pickwareType = jo.getInteger("pickwareType");
        //返件方式
        Integer returnwareType = jo.getInteger("returnwareType");
        //用户id
        String adminId = jo.getString("adminid");
        //申请原因
        String reason = jo.getString("reason");
        String returnAddr = jo.getString("returnAddr");
        String takeAddr = jo.getString("takeAddr");
        Map<String, Object> params = new HashMap<>();
        //组装数据
        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        ztGoodsOrder.setId(orderId);
        ztGoodsOrder = ztGoodsOrderService.get(ztGoodsOrder);
        params.put("jdOrderId", ztGoodsOrder.getChannelorder());
        params.put("customerExpect", customerExpect);
        params.put("questionDesc", questionDesc);
        params.put("isNeedDetectionReport", Boolean.TRUE);
        params.put("questionPic", questionPic);
        params.put("isHasPackage", Boolean.TRUE);
        params.put("packageDesc", 0);
        // 组装客户实体
        params.put("asCustomerDto",afterSaleCustomer(ztGoodsOrder));
        // 组装取件实体
        params.put("asPickwareDto",afterSalePickware(pickwareType, ztGoodsOrder,jo));
        //组装返件地址
        params.put("asReturnwareDto",afterSaleReturnware(returnwareType, ztGoodsOrder,jo));
        // 组装明细
        params.put("asDetailDto",afterSaleDetail(ztGoodsOrder));
        //保存数据
        AfterSaleServiceCreateDto.AfterSaleAfsApplyCreateBean after = ProductPoolUtils.serviceApplication(GsonUtil.toJson(params));
        if (after.isSuccess()) {
            ZtAfterSale sale = saveAfterSale(customerExpect,reason,adminId,ztGoodsOrder,returnAddr,takeAddr,pickwareType,questionDesc,questionPic);
            saveServiceSingle(ztGoodsOrder.getChannelorder(),sale.getId());
        if (StringUtils.isEmpty(sale)) {
            res.setResult(400L);
            res.setMsg("保存异常!");
            Render.renderString(response, res);
            return;
        }
            AfterSaleListVo listVo = new AfterSaleListVo();
            listVo.setNumCount(ztGoodsOrder.getNumCount());
            listVo.setImg(sale.getImg());
            listVo.setTitle(sale.getWareName());
            listVo.setSaleId(sale.getId());
            res.setResult(200L);
            res.setData(listVo);
            Render.renderString(response, res);
            return;
        }
        res.setResult(400L);
        res.setRecode(after);
        Render.renderString(response, res);
    }

    @PostMapping(value = "createTwo")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public void createServiceTwo(HttpServletRequest request,HttpServletResponse response){
        String paramStr=CommonUtils.getParams(request);
        JSONObject jo=JSONObject.parseObject(paramStr);
        ResultObject res = new ResultObject();
        if (StringUtils.isEmpty(jo.getString("returnAddr")) & StringUtils.isEmpty(jo.getString("adminid"))) {
            res.setResult(400L);
            res.setMsg("非法参数!");
            Render.renderString(response, res);
        }

        ZtAfterSale ztAfterSale = new ZtAfterSale();
        //订单号
        String orderId = jo.getString("orderId");
        //客户预期（退货(10)、换货(20)、维修(30)）
        Integer customerExpect = jo.getInteger("customerExpect");
        //产品问题描述
        String questionDesc = jo.getString("questionDesc");
        //问题描述图片 url1,url2
        String questionPic = jo.getString("questionPic");
        // 取件方式
        Integer pickwareType = jo.getInteger("pickwareType");
        //返件方式
        Integer returnwareType = jo.getInteger("returnwareType");
        //用户id
        String adminId = jo.getString("adminid");
        //申请原因
        String reason = jo.getString("reason");
        String returnAddr = jo.getString("returnAddr");
        String takeAddr = jo.getString("takeAddr");

        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        ztGoodsOrder.setId(orderId);
        ztGoodsOrder = ztGoodsOrderService.get(ztGoodsOrder);
        if(ztGoodsOrder==null){
            res.setResult(400L);
            res.setMsg("订单不存在!");
            Render.renderString(response, res);
            return;
        }
        ztAfterSale.setAdminId(adminId);
        ztAfterSale.setOrder(orderId);
        ztAfterSale.setType(customerExpect);
        ztAfterSale.setTakeType(returnwareType);
        ztAfterSale.setSpotid(0);
        ztAfterSale.setReason(reason);
        ztAfterSale.setReturnAddr(returnAddr);
        ztAfterSale.setTakeAddr(takeAddr);
        ztAfterSale.setAfsServiceStep(AfsServiceEnum.APPLYING.getValue());
        ztAfterSale.setAfsServiceStepName(AfsServiceEnum.APPLYING.getName());
        ztAfterSale.setCancel(true);
        ztAfterSale.setImg(ztGoodsOrder.getZtGoods().getImg());
        ztAfterSale.setNum(ztGoodsOrder.getNumCount());
        ztAfterSale.setWareName(ztGoodsOrder.getZtGoods().getTitle());
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ztAfterSale.setAfsApplyTime(sdf.format(d));
        ztAfterSale.setCreateDate(d);
        ztAfterSale.setQuestionDesc(questionDesc);
        ztAfterSale.setQuestionPic(questionPic);
        ztAfterSale.setSkuId(ztGoodsOrder.getSku());
//        ztAfterSale.setAfsServiceId();
        ztAfterSaleService.save(ztAfterSale);
        ztGoodsOrder.setSalestatus("2");
        ztGoodsOrderService.update(ztGoodsOrder);
        res.setResult(200L);
        res.setData("保存成功");
        Render.renderString(response, res);
        return;

    }


    /**
     *  填写发运信息
     * @param request
     * @param response
     */
    @PostMapping(value = "shipping")
    @ResponseBody
    public void shippingInfo(HttpServletRequest request,HttpServletResponse response){
        ResultObject res = new ResultObject();
        String paramStr=CommonUtils.getParams(request);
        JSONObject jo=JSONObject.parseObject(paramStr);
        String afsServiceId = jo.getString("afsServiceId");
        //运费
        String freightMoney = jo.getString("freightMoney");
        String expressCompany = jo.getString("expressCompany");
        String deliverDate = jo.getString("deliverDate");
        String expressCode = jo.getString("expressCode");
        ZtAfterSale afterSale = new ZtAfterSale();
        afterSale.setId(afsServiceId);
        afterSale = ztAfterSaleService.get(afterSale);
        if(afterSale.getSpotid()==1){
            if (AddSshippingInfo(freightMoney, expressCompany, deliverDate, expressCode, afterSale)) {
                afterSale.setFreightMoney(freightMoney);
                afterSale.setExpressCompany(expressCompany);
                afterSale.setDeliverDate(deliverDate);
                afterSale.setExpressCode(expressCode);
                ztAfterSaleService.update(afterSale);
                res.setResult(200L);
                Render.renderString(response, res);
                return;
            }
        }else {
            afterSale.setAfsServiceStep(AfsServiceEnum.OFGOODS.getValue());
            afterSale.setAfsServiceStepName(AfsServiceEnum.OFGOODS.getName());
            afterSale.setFreightMoney(freightMoney);
            afterSale.setExpressCompany(expressCompany);
            afterSale.setDeliverDate(deliverDate);
            afterSale.setExpressCode(expressCode);
            ztAfterSaleService.update(afterSale);
            res.setResult(200L);
            Render.renderString(response, res);
            return;
        }

        res.setResult(400L);
        res.setMsg("内部异常!");
        Render.renderString(response, res);
    }

    /**
     *  取消售后
     * @param request
     * @param response
     */
    @RequestMapping(value = "cancel")
    @ResponseBody
    public void cancelAfterSale(HttpServletRequest request,HttpServletResponse response){
        ResultObject res = new ResultObject();
        String paramStr=CommonUtils.getParams(request);
        JSONObject jo=JSONObject.parseObject(paramStr);
        String saleId = jo.getString("saleId");
        ZtAfterSale afterSale = new ZtAfterSale();
        afterSale.setId(saleId);
        afterSale = ztAfterSaleService.get(afterSale);
        afterSale.setAfsServiceStep(60);
        afterSale.setAfsServiceStepName("取消");
        if(afterSale.getSpotid()==1){
            Map<String, Object> params = new HashMap<>();
            params.put("serviceIdList", Arrays.asList(afterSale.getAfsServiceId()));
            params.put("approveNotes","允许取消");
            if (ProductPoolUtils.auditCancel(GsonUtil.toJson(params))) {
                ztAfterSaleService.update(afterSale);
                ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
                ztGoodsOrder.setId(afterSale.getOrder());
                ztGoodsOrder.setSalestatus("4");
                ztGoodsOrderService.update(ztGoodsOrder);
                res.setResult(200L);
                Render.renderString(response, res);
                return;
            }
        }else {
            ztAfterSaleService.update(afterSale);
            ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
            ztGoodsOrder.setId(afterSale.getOrder());
            ztGoodsOrder.setSalestatus("4");
            ztGoodsOrderService.update(ztGoodsOrder);
            res.setResult(200L);
            Render.renderString(response, res);
            return;
        }

        res.setResult(400L);
        res.setMsg("非法参数!");
        Render.renderString(response, res);
    }


    /** 获取服务类型 */
    private String getServiceType(Integer serviceType) {
        String type = null;
        switch (serviceType) {
            case 10:
                type = "退货";
                break;
            case 20:
                type = "换货";
                break;
            case 30:
                type = "维修";
                break;
            default:
                type = "退货";
        }
        return type;
    }

    /**
     *  保存数据
     * @param customerExpect
     * @param reason
     * @param adminId
     * @param ztGoodsOrder
     * @return
     */
    private ZtAfterSale saveAfterSale(Integer customerExpect,String reason, String adminId, ZtGoodsOrder ztGoodsOrder,
                                      String returnAddr,String takeAddr,Integer pickwareType,String questionDesc,String questionPic) {
        ZtAfterSale sale = new ZtAfterSale();
        sale.setOrder(ztGoodsOrder.getId());
        sale.setWareName(ztGoodsOrder.getZtGoods().getTitle());
        sale.setImg(ztGoodsOrder.getZtGoods().getImg());
        sale.setNum(ztGoodsOrder.getNumCount());
        sale.setReason(reason);
        sale.setReturnAddr(returnAddr);
        sale.setSkuId(ztGoodsOrder.getSku());
        sale.setAdminId(adminId);
        sale.setType(customerExpect);
        sale.setTakeAddr(takeAddr);
        sale.setCreateDate(new Date());
        sale.setTakeType(pickwareType);
        sale.setQuestionDesc(questionDesc);
        sale.setQuestionPic(questionPic);
        ztGoodsOrder.setSalestatus("2");
        ztGoodsOrderService.update(ztGoodsOrder);
        ztAfterSaleService.save(sale);
        return sale;
    }

    /**
     *  共用
     * @param request
     * @param res
     * @return
     */
    private Map<String, Object> shareParameter(HttpServletRequest request,ResultObject res) {
        String paramStr = CommonUtils.getParams(request);
        JSONObject json = JSONObject.parseObject(paramStr);
        Map<String, Object> params = new HashMap<>();
        String orderId = json.getString("orderId");
        ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
        ztGoodsOrder.setId(orderId);
        ztGoodsOrder = ztGoodsOrderService.get(ztGoodsOrder);
        if (!ztGoodsOrder.getState().equals("1")) {
            res.setResult(400L);
            res.setMsg("商品还为签收");
            return null;
        }
        params.put("spotid",ztGoodsOrder.getSpotid());
        params.put("jdOrderId", ztGoodsOrder.getChannelorder());
        params.put("skuId", ztGoodsOrder.getSku());
        params.put("order", ztGoodsOrder);
        return params;
    }


    /**
     *  添加发运信息
     * @param freightMoney
     * @param expressCompany
     * @param deliverDate
     * @param expressCode
     * @param afterSale
     * @return
     */
    private Boolean AddSshippingInfo(String freightMoney, String expressCompany, String deliverDate, String expressCode, ZtAfterSale afterSale) {
        Map<String, Object> params = new HashMap<>();
        params.put("afsServiceId", afterSale.getAfsServiceId());
        params.put("freightMoney", new BigDecimal(freightMoney));
        params.put("expressCompany", expressCompany);
        params.put("deliverDate", deliverDate);
        params.put("expressCode", expressCode);
        return ProductPoolUtils.fillInClientShippingInfo(GsonUtil.toJson(params));
    }

    /**
     *  保存服务单
     * @param order
     */
    public synchronized void saveServiceSingle(String order,String afterSaleId) {
        try {
            Thread.sleep(2500);
            Map<String, Object> params = new HashMap<>();
            params.put("jdOrderId", order);
            params.put("pageIndex", 1);
            params.put("pageSize", 10);
            ServiceSingleDto dto = ProductPoolUtils.queryServiceApplication(GsonUtil.toJson(params));
            ServiceSingleDto.BizAfterSaleServiceListPageQueryResponseBean.ResultBean.ServiceInfoListBean listBean
                    = dto.getBiz_afterSale_serviceListPage_query_response().getResult().getServiceInfoList().get(0);
            if (listBean.getAfsServiceStep().equals(60)) {
                saveServiceSingle(order,afterSaleId);
            }else {
                ZtAfterSale afterSale = new ZtAfterSale();
                afterSale.setId(afterSaleId);
                afterSale = ztAfterSaleService.get(afterSale);
                BeanUtils.copyProperties(listBean, afterSale);
                afterSale.setSpotid(1);
                ztAfterSaleService.update(afterSale);
                ZtGoodsOrder ztGoodsOrder = new ZtGoodsOrder();
                ztGoodsOrder.setId(afterSale.getOrder());
                ztGoodsOrder.setSalestatus("2");
                ztGoodsOrderService.update(ztGoodsOrder);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  组装明细
     * @param ztGoodsOrder
     * @return
     */
    private AfterSaleDetailDto afterSaleDetail(ZtGoodsOrder ztGoodsOrder) {
        AfterSaleDetailDto detailDto = new AfterSaleDetailDto();
        detailDto.setSkuId(ztGoodsOrder.getSku());
        detailDto.setSkuNum(ztGoodsOrder.getNumCount());
        return detailDto;
    }

    /**
     * 组装返件地址
     * @param returnwareType
     * @param ztGoodsOrder
     * @return
     */
    private AfterSaleReturnwareDto afterSaleReturnware(Integer returnwareType, ZtGoodsOrder ztGoodsOrder,JSONObject jo) {
        AfterSaleReturnwareDto returnwareDto = new AfterSaleReturnwareDto();
        if (jo.getString("takeAddrDto").length() > 75){
            ReturnAddrVo returnDto = GsonUtil.parse(jo.getString("returnDto"), ReturnAddrVo.class);
            returnwareDto.setReturnwareType(returnwareType);
            returnwareDto.setReturnwareProvince(returnDto.getProvincebid());
            returnwareDto.setReturnwareCity(returnDto.getCitybid());
            returnwareDto.setReturnwareCounty(returnDto.getCountybid());
            returnwareDto.setReturnwareVillage(returnDto.getTownbid());
            returnwareDto.setReturnwareAddress(returnDto.getDetailaddr());
            return returnwareDto;
        }else {
            returnwareDto.setReturnwareType(returnwareType);
            returnwareDto.setReturnwareProvince(ztGoodsOrder.getProvincebid());
            returnwareDto.setReturnwareCity(ztGoodsOrder.getCitybid());
            returnwareDto.setReturnwareCounty(ztGoodsOrder.getCountybid());
            returnwareDto.setReturnwareVillage(ztGoodsOrder.getTownbid());
            returnwareDto.setReturnwareAddress(ztGoodsOrder.getDetailaddr());
            return returnwareDto;
        }
    }

    /**
     * 组装取件实体
     * @param pickwareType
     * @param ztGoodsOrder
     * @return
     */
    private AfterSalePickwareDto afterSalePickware(Integer pickwareType, ZtGoodsOrder ztGoodsOrder,JSONObject jo) {
        AfterSalePickwareDto pickwareDto = new AfterSalePickwareDto();
        if (jo.getString("takeAddrDto").length() > 75){
            TakeAddrVo takeAddrDto = GsonUtil.parse(jo.getString("takeAddrDto"), TakeAddrVo.class);
            pickwareDto.setPickwareType(pickwareType);
            pickwareDto.setPickwareProvince(takeAddrDto.getProvincebid());
            pickwareDto.setPickwareCity(takeAddrDto.getCitybid());
            pickwareDto.setPickwareCounty(takeAddrDto.getCountybid());
            pickwareDto.setPickwareVillage(takeAddrDto.getTownbid());
            pickwareDto.setPickwareAddress(takeAddrDto.getDetailaddr());
            return pickwareDto;
        }else {
            pickwareDto.setPickwareType(pickwareType);
            pickwareDto.setPickwareProvince(ztGoodsOrder.getProvincebid());
            pickwareDto.setPickwareCity(ztGoodsOrder.getCitybid());
            pickwareDto.setPickwareCounty(ztGoodsOrder.getCountybid());
            pickwareDto.setPickwareVillage(ztGoodsOrder.getTownbid());
            pickwareDto.setPickwareAddress(ztGoodsOrder.getDetailaddr());
            return pickwareDto;
        }

    }

    /**
     * 组装客户实体
     * @param ztGoodsOrder
     * @return
     */
    private AfterSaleCustomerDto afterSaleCustomer(ZtGoodsOrder ztGoodsOrder) {
        AfterSaleCustomerDto dto = new AfterSaleCustomerDto();
        dto.setCustomerContactName(ztGoodsOrder.getName());
        dto.setCustomerMobilePhone(ztGoodsOrder.getPhone());
        dto.setCustomerTel(ztGoodsOrder.getPhone());
        return dto;
    }

    public List<AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean> serviceType(){
        List<AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean> resultBeans = new ArrayList<>();
        AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean resultBean = new AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean();
        resultBean.setCode("10");
        resultBean.setName("退货");
        resultBean.setDepict("退掉已收到的商品");
        resultBeans.add(resultBean);
        AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean resultBean1 = new AfterSaleStandByProductDto.AfterSaleStandByProduct.ResultBean();
        resultBean1.setCode("20");
        resultBean1.setName("换货");
        resultBean1.setDepict("更换收到的商品");
        resultBeans.add(resultBean1);
        return resultBeans;
    }

}
